import { logoutApi, videoSearchApi } from './axiosapi.js'

const { ref, reactive } = Vue

export const store = reactive({
  user: JSON.parse(sessionStorage.getItem('CURRENT_USER')),
  videos: [],

  async setVideos(keyword){
    this.videos = await videoSearchApi(keyword)
  },

  setUser(currentUser) {
    let isAdmin = currentUser.authorities.map(it => it.authority).includes('ROLE_ADMIN')
    Object.assign(currentUser, { isAdmin })
    this.user = currentUser
    sessionStorage.setItem('CURRENT_USER', JSON.stringify(currentUser))
  },

  async clearUser(isLogoutApi) {
    console.log('Session Storage Remove Item: Current User')
    if(isLogoutApi === true){
      await logoutApi()
    }
    this.user = null
    sessionStorage.removeItem('CURRENT_USER')
  },

  getMenus() {
    const menus = [{ key: '/', title: '主页', icon: 'fa fa-home', type: 'text' }]
    if(!this.user){
      menus.push({ key: '/register', title: '注册', icon: 'fa fa-user-plus', type: 'text' })
      menus.push({ key: '/login', title: '登录', icon: 'fa fa-sign-in', type: 'text' })
    }else{
      if(!!this.user){
        const avatarImg = ''
        menus.push({ key: '/video/list', title: this.user.nickname, src: avatarImg, type: 'text' })
      }
      if(!!this.user && this.user.isAdmin){
        menus.push({ key: '/users', title: '用户列表', icon: 'fa fa-users', type: 'text' })
        menus.push({ key: '/cate/add', title: '添加视频类别', icon: 'fa fa-plus-circle', type: 'text' })
      }
      menus.push({ key: '/video/add', title: '添加视频', icon: 'fa fa-plus-circle', type: 'text' })
      menus.push({ key: '/logout', title: '退出', icon: 'fa fa-sign-out', type: 'text' })
    }
    const router = VueRouter.useRouter()
    const path = router.currentRoute.value.path
    menus.forEach(it => {
      if(it.key === path){
        it.type = 'link'
      }
    })
    return menus
  }
})
